package com.yao.fin.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.word.Word07Writer;
import cn.hutool.poi.word.WordUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.fin.entity.FinancialTemplateEntity;
import com.yao.fin.entity.dto.FinancialTemplateDto;
import com.yao.fin.entity.qo.FinancialTemplateQo;
import com.yao.fin.enums.CourseBase;
import com.yao.fin.enums.LabelEnum;
import com.yao.fin.enums.SingleEnum;
import com.yao.fin.mapper.FinancialTemplateMapper;
import com.yao.fin.service.FinancialTemplateService;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 财务模版表 接口实现
 *
 * @author autoCode
 * @version 1.0.0-SNAPSHOT
 * @date 2020-03-12
 */
@Service
public class FinancialTemplateServiceImpl extends ServiceImpl<FinancialTemplateMapper, FinancialTemplateDto>
    implements FinancialTemplateService {

    @Autowired
    private FinancialTemplateMapper mapper;

    @Override
    public IPage<FinancialTemplateDto> listpage(Page<FinancialTemplateQo> page, FinancialTemplateQo qo) {

        IPage<FinancialTemplateDto> ipage = mapper.listpage(page, qo.buildParams());
        List<FinancialTemplateDto> collect = ipage.getRecords().stream().map(e -> FinancialTemplateDto.of(e).fill()).collect(Collectors.toList());
        ipage.setRecords(collect);
        return ipage;
    }


    @Override
    public String export(FinancialTemplateQo qo) {
        // 读取数据
        LambdaQueryWrapper<FinancialTemplateDto> wrapper = Wrappers.lambdaQuery();
        qo = qo.buildParams();
        wrapper.eq(FinancialTemplateEntity::getLabel, qo.getLabel())
                .ge(null != qo.getBeginDate(), FinancialTemplateEntity::getTrainDate, qo.getBeginDate())
                .le(null != qo.getEndDate(), FinancialTemplateEntity::getTrainDate, qo.getEndDate())
                .orderByAsc(FinancialTemplateEntity::getTrainDate);

        List<FinancialTemplateDto> list = list(wrapper);
//        List<FinancialTemplateEntity> list = null;

        // 按习题时间分类 并对key进行排序
        Map<String, List<FinancialTemplateDto>> byDate = list.stream()
                .collect(Collectors.groupingBy(FinancialTemplateEntity::getTrainDate))
                .entrySet().stream()
                .sorted(Map.Entry.comparingByKey())
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));

        // 写word文件
        String fileName = LabelEnum.getDesc(qo.getLabel()) + qo.getBeginDate() + " - " + qo.getEndDate() + StrUtil.sub(UUID.fastUUID().toString(), 0 ,3) + ".docx";
        Word07Writer wordWrite = WordUtil.getWriter(FileUtil.newFile("/Users/yymlbx201314/Desktop/"+fileName));

        Font font = new Font("微软雅黑", Font.BOLD, 13);
        Font varFont = new Font("微软雅黑", Font.PLAIN, 13);
        byDate.forEach((date, dayList) -> {
            wordWrite.addText(font,date);

            // 写题目
            dayList.stream().sorted(Comparator.comparing(FinancialTemplateEntity::getCourse)).forEach(e -> {
                Integer course = e.getCourse();
                Integer singelFlag = e.getSingle();
//                wordWrite.addText(font,course + "、" + CourseBase.ZJEnum.getDesc(course)+"（"+ SingleEnum.getDesc(singelFlag)+"）");
                XWPFParagraph paragraph = wordWrite.getDoc().createParagraph();
                XWPFRun run1 = paragraph.createRun();
                run1.setBold(true);
                run1.setFontSize(13);
                run1.setFontFamily("微软雅黑");
                if(e.getLabel().equals(LabelEnum.ZJ.getCode())){
                    run1.setText(CourseBase.ZJEnum.getDesc(course));
                }else if(e.getLabel().equals(LabelEnum.CPA.getCode())){
                    run1.setText(CourseBase.CPAEnum.getDesc(course));
                }

                XWPFRun run2 = paragraph.createRun();
                run2.setBold(true);
                run2.setColor("FF0000");
                run2.setFontSize(13);
                run2.setFontFamily("微软雅黑");
                run2.setText("（"+ SingleEnum.getDesc(singelFlag)+"）");
                wordWrite.addText(varFont, course + "、" + e.getQuestion());
            });

            wordWrite.addText(font,"\n\r");

            // 写答案
            dayList.stream().sorted(Comparator.comparing(FinancialTemplateEntity::getCourse)).forEach(e -> {

                wordWrite.addText(font,e.getCourse() + "、参考答案：", e.getAnswer().toUpperCase());
                wordWrite.addText(font,"解析：", e.getExplain());
            });

            wordWrite.addText(font,"\n\r");
            wordWrite.addText(font,"\n\r");

        });

        wordWrite.flush();
        wordWrite.close();

        return fileName;
    }




}